let Sequelize = require('sequelize');
let Op = Sequelize.Op;

let Picture = require('../models/Picture');
let User =  require('../models/User');
let attributes = [
    'id',
    'label',
    'address',
    'user_id',
    'created_at',
    'updated_at'
];

class PictureService {
    static async getPicList(param) {
        let page_num = Number(param.page_num) || 1,
            limit = Number(param.page_size) || 10;
        let offset = page_num == 1 ? 0 : limit * ( page_num - 1 );
        let where = {
            file_type: param.file_type, 
            is_deleted: 0 
        };
        if(param.label) where.label = { [Op.like]: `%${param.label}%` };
        let includeWhere = {};
        if(param.user_name) {
            includeWhere = {
                name: {
                    [Op.like]: `%${param.user_name}%`
                }
            }
        }
        let order = [['updated_at', 'desc']];
        let include = [{ // include关键字表示关联查询
            model: User, // 指定关联的model
            as:'user', // 由于前面建立映射关系时为class表起了别名，那么这里也要与前面保持一致，否则会报错
            where: includeWhere,
            attributes: [['name', 'userName']]
        }];
        try {
            let result = null;
            if(param.file_type.includes('tourist_image')) {
                result = await Picture.findAndCountAll({ attributes, where, offset, limit, order });
            } else {
                result = await Picture.findAndCountAll({ attributes, where, offset, limit, include, order });
            }
            result.rows.map(el => el['dataValues'].thumbnail = $utils._resize(el.address));
            return {
                total: result.count,
                list: result.rows,
                page_num,
                page_size: limit
            }
        } catch (e) {
            return e.stack;
        }
    }
    static async createPic(param) {
        try {
            param.user_id = param.operator_id;
            return await Picture.create(param);
        } catch (e) {
            return e.stack
        }
    }
    static async findPic({ id }) {
        let include = [{
            model: User,
            as:'user',
            attributes: [['name', 'userName']]
        }];
        try {
            return await Picture.findOne({ attributes, include, where: { id }});
        } catch (e) {
            return e.stack
        }
    }
    static async updatePic(param) {
        try {
            return await Picture.update(param, { where: { id: param.id } });
        } catch (e) {
            return e.stack
        }
    }
    static async deletePic({ id }) {
        try {
            return await Picture.update({is_deleted: 1}, {where: { id }});
        } catch (e) {
            return e.stack
        }
    }
}

module.exports = PictureService;
